# -*- coding: utf-8 -*-
from apps.account.weibo import APIClient, APIError
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib import auth
from django.contrib.auth.models import User
from apps.account.models import Account
from django.contrib.auth.decorators import login_required
import urllib
import threading
import datetime
from django.http import HttpRequest 
from django.template import RequestContext

# TODO www 永久定向到 裸域
# TODO 登录时，提示等待
# TODO 并行处理登录环节，或者显示展示跳转，不然等待太久。
# apache rewrite 到裸域

APP_KEY = '1287215741' # app key
APP_SECRET = '4a85799b81eb3aee38009c5a051f5249' # app secret
CALLBACK_URL = 'http://xingtanlu.com/account/weiboauthcallback/' # callback url


def byrauth(request):
    form_fields = { 
      "id": 'liaksc', 
      "passwd": 'h', 
      "save": False
    } 
    URL = 'http://m.byr.cn/user/login'
    params = urllib.urlencode(form_fields) 
    f = urllib.urlopen(URL, params)
    if f.code != 200: 
        return HttpResponse('fail')
    
    # 思路是进行字符串处理 <div class="sp hl f">登陆成功</div>
    
    return HttpResponse(f)        
    

@login_required
def test(request):
    return render_to_response('account/test.html',{
                        #'form': form
                        }, context_instance=RequestContext(request))

def login(request):
    if request.method == 'POST':
        pass;
    
    # 返回登陆前的页面
    if 'next' in request.GET and request.GET['next']:
        next = request.GET['next']
    else:
        next = request.META.get('HTTP_REFERER','/')
    
    return render_to_response('account/login.html',{
                        #'form': form
                        }, context_instance=RequestContext(request))


def logout(request):
    auth.logout(request)
    next = request.META.get('HTTP_REFERER','/')
    return HttpResponseRedirect('/')

# 登录调用杏坛路，耗时
def weiboauth(request):
    # 返回登陆前的页面
    if 'next' in request.GET and request.GET['next']:
        next = request.GET['next']
    else:
        next = request.META.get('HTTP_REFERER','/')
        
    # NEXT 返回登陆前的页面
    CALLBACK_URL = 'http://xingtanlu.com/account/weiboauthcallback/?&next=' + next
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()
    
    #https://api.weibo.com/oauth2/authorize?redirect_uri=
    #http%3A//xingtanlu.com/account/weiboauthcallback/
    #&response_type=code&client_id=1287215741&display=default    
    # 第一次调用新浪API ，耗时。
    return HttpResponseRedirect(url)

# 回调杏坛路，耗时。只做知道USER是谁，即拿到TOKEN、UID信息的功能，哈哈关注杏坛路
def weiboauthcallback(request):
    # 返回登陆前的页面
    if 'next' in request.GET and request.GET['next']:
        next = request.GET['next']
    else:
        next = request.META.get('HTTP_REFERER','/')
        
    # 获取URL参数code:
    code = request.GET['code']
    # r = response 调用新浪API
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()
    
    # 第二次调用API,耗时 是服务器调用。
    r = client.request_access_token(code)
    
    uid = r.uid
    token = r.access_token
    expire = r.expires_in
    client.set_access_token(token, r.expires_in)
    
    #clientA
    clientA = client
    
    # 第三次服务器调用新浪API....耗时。。。 读取用户信息，返回的是json {'a':'b', ...}
    r = clientA.get.users__show(uid=uid)
    spic = r['profile_image_url']
    lpic = r['avatar_large']
    description = r['description']
    gender = r['gender']
    first_name = r['name']    
    
    
    # 用户数据入库
    try:
        tuser = User.objects.get(username = uid)
    # 第一次登录
    except User.DoesNotExist:
        tuser =User.objects.create_user(username=uid, email=uid + '@xingtanlu.com',password=uid)
        tuser.first_name = first_name
        tuser.save()
        
        #关注 杏坛路
        threadGetFriends = threading.Thread(target=guanzhu, kwargs={'token':token, 'expire':expire})
        threadGetFriends.setDaemon(True)
        threadGetFriends.start()
        
        
    try:
        account = Account.objects.get(user=tuser)
        
    # 第一次登录
    except Account.DoesNotExist:
        account = Account.objects.create(user = tuser, 
                                spic = spic, 
                                lpic = lpic,
                                token = token,
                                description = description,
                                gender = gender
                                )

    # Login & set session expire time,登录一次续期一个月
    tuser = auth.authenticate(username=uid, password=uid)
    if tuser is not None:
        auth.login(request, tuser)
        sessionExpireTime = datetime.timedelta(days=28)
        request.session.set_expiry(sessionExpireTime)   
        return HttpResponseRedirect(next) 
    
    return HttpResponse('weiboauthcallback fail') 


#自动关注 @杏坛路
def guanzhu(**kwargs):
    CALLBACK_URL = 'http://xingtanlu.com/account/weiboauthcallback/'
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()  
        
    client.set_access_token(access_token=kwargs['token'], expires_in=kwargs['expire'])
    client.post.friendships__create(uid='2881776540')
    return None
    
